/**
 * 
 */
package com.hson.demo.web.base.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hson.demo.base.constant.BaseConstants;
import com.hson.demo.base.controller.DataAccessController;


/**
 * 本应用统一使用的控制器父类
 * 
 * @author Hungel.zou
 * @since 2013-8-30 下午1:51:20
 * @version 1.0
 */
public abstract class AbstractController extends DataAccessController {

	protected static final Logger logger = LoggerFactory.getLogger(AbstractController.class);

	protected static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	
	/**
	 * 获得地址
	 * 
	 * @param processUrl
	 * @param returnUrl
	 * @param authId
	 * @param defaultUrl
	 * @return
	 */
	protected String getView(String processUrl, String returnUrl, String authId) {
		if (!StringUtils.isBlank(processUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(processUrl).append("?").append(BaseConstants.AUTH_KEY).append("=")
					.append(authId);
			if (!StringUtils.isBlank(returnUrl)) {
				sb.append("&").append(BaseConstants.RETURN_URL).append("=").append(returnUrl);
			}
			return sb.toString();
		} else if (!StringUtils.isBlank(returnUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(returnUrl);
			return sb.toString();
		} else {
			return null;
		}
	}
	
	protected void setMsg(HttpServletRequest request, String msg){
		request.getSession().setAttribute("msg", msg);
	}
	
	protected void clearMsg(HttpServletRequest request){
		request.getSession().removeAttribute("msg");
	}
	
	/**
	 * 判断是否登录
	 * 
	 * @return
	 * @throws Exception
	 */
	protected boolean isLogin() throws Exception{
		return getSession().getAttribute(BaseConstants.USER)!=null;
	}
	
	/**
	 * 输出提示信息，指定输出消�?
	 * 
	 * @param response
	 * @param msg
	 */
	protected void writeMsg(HttpServletResponse response, String msg) {
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			out.write(msg.getBytes("UTF-8"));
			out.flush();

			logger.info(msg);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("" + e);
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					//
				}
		}
	}
	

}
